package com.cly.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cly.base.contants.CacheKeysConstants;
import com.cly.entity.ProblemOption;
import com.cly.enums.ProblemTypeEnum;
import com.cly.mapper.ProblemOptionMapper;
import com.cly.result.JsonRequest;
import com.cly.result.exception.ServiceException;
import com.cly.result.exenum.RequestException;
import com.cly.service.IProblemOptionService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 题目选项表 服务实现类
 *
 * @author by 春风能解释
 * <p>
 * 2024-06-05
 */
@Service
public class ProblemOptionServiceImpl extends ServiceImpl<ProblemOptionMapper, ProblemOption> implements IProblemOptionService {


    /**
     * 添加选项
     *
     * @param options   选项列表
     * @param type      题目类型
     * @param problemId 题目ID
     * @return JSON
     */
    @Override
    @CacheEvict(value = CacheKeysConstants.ExamKeys.PROBLEM_ARRAY, allEntries = true)
    public JsonRequest<Integer> insertOption(List<ProblemOption> options, Integer type, Long problemId) {
        // 判断是否为简答题
        if (type.equals(ProblemTypeEnum.SHORT_ANSWER.getValue()) && !ArrayUtil.isArray(options)) {
            return JsonRequest.success();
        }
        // 单选题:答案个数不得>1
        if (type.equals(ProblemTypeEnum.SINGLE_CHOICE.getValue())) {
            long count = options
                    .stream()
                    .filter(ProblemOption::getIsAnswer)
                    .count();
            if (count > 1) {
                return JsonRequest.error(RequestException.INSERT_ERROR);
            }
        }
        // 判断题:选项总数不得>2
        else if (type.equals(ProblemTypeEnum.JUDGMENT.getValue()) && options.size() > 2) {
            return JsonRequest.error(RequestException.INSERT_ERROR);
        }
        // 判断选项是否为空
        if (options.isEmpty()) {
            throw new ServiceException(RequestException.INSERT_ERROR);
        }
        // 设置题目id
        options.forEach(v ->
                v.setProblemId(problemId)
                        .setId(null)
                        .setUpdateUser(null)
                        .setUpdateTime(null));
        return JsonRequest.success(baseMapper.insert(options).size());
    }

}